import streamlit as st
import re
import os
import requests
import time
from io import BytesIO
import hashlib
from utils.sha1utils import calculate_sha1


st.set_page_config(layout="wide")

gradle_mirror = 'https://mirrors.cloud.tencent.com/gradle/'

if 'gradles' not in st.session_state:
    st.session_state['gradles'] = []
    gradles = re.findall(r'(gradle-[^\bzip\b]+.zip)\s', open('data/gradle-list.txt').read())
    st.session_state['gradles'] = gradles
    st.rerun()

gradles = st.session_state['gradles']

gradle_dists = '.gradle/wrapper/dists/'
gradle_caches = '.gradle/caches/modules-2/files-2.1/gradle/gradle/'

def curl(url):
    resp = requests.get(url, stream=True)

    for chunk in resp.iter_content(chunk_size=1024):
        yield chunk

Page = [
    '本地',
    '镜像站'
]


p = st.sidebar.selectbox('选择镜像源', Page)

st.title('欢迎使用 Gradle 镜像')

if p == '本地':

    gradle_dists_dir = os.path.join(os.getenv('HOME'), gradle_dists)
    gradle_versions = []

    for i in os.listdir(gradle_dists_dir):
        if i.startswith('gradle'):
            gradle_versions.append(i)

    gradle_versions.sort()

    gradle_version = st.sidebar.selectbox('选择 Gradle 版本', gradle_versions)
    if gradle_version:
        st.write(f'你选择了:  {gradle_version}')

        gradle_version_dir = os.path.join(gradle_dists_dir, gradle_version)
        st.write(gradle_version_dir)
        
        gradle_version_hash_dirs = []
        
        version_hashmap = {}
        for version_hash in os.listdir(gradle_version_dir):
            version_hash_dir = os.path.join(gradle_version_dir, version_hash)
            
            if os.path.isdir(version_hash_dir):
                # 'check *.zip'
                for i in os.listdir(version_hash_dir):
                    if i.endswith('.zip'):
                        version_hashmap[version_hash] = i
            
            # check again
            if version_hash not in version_hashmap:
                version_hashmap[version_hash] = '未下载'

            gradle_version_hash_dirs.append(version_hash_dir)

        st.table(version_hashmap)


        # use requests download it
        # use mirrors
        # save gradle to version_hash_dir

        if '未下载' in version_hashmap.values():
            st.warning('存在未下载的 Gradle')

            st.write('将下载 Gradle 保存到以下目录')
            for i in gradle_version_hash_dirs:
                st.write(i)
            
            if st.button('下载 gradle'):
                download_url = gradle_mirror + gradle_version + '.zip'

                # 进行下载前的可访问性检查
                with st.spinner('资源探测中...'):
                    head = requests.head(download_url)
                    try:
                        head.raise_for_status()
                    except requests.exceptions.HTTPError:
                        st.error('探测失败，停止下载')
                        st.error(head.text)
                        st.stop()
                    else:
                        st.write('探测成功, 准备下载')
                        time.sleep(2)

                # 当响应头中包含 Content-Length，则明确指定了资源大小
                if 'Content-Length' in head.headers:
                    with st.expander('请求头'):
                        st.json(dict(head.headers))

                    total_length = int(head.headers['Content-Length'])
                    st.write('资源大小: {:.2f}mb'.format(total_length/1024/1024))

                    with st.spinner('下载中...'):
                        pbar = st.progress(0, '下载中...')
                        
                        resp = curl(download_url)

                        filememory = BytesIO()
                        download_length = 0
                        for chunk in resp:
                            filememory.write(chunk)
                            download_length += len(chunk)
                            pbar.progress(float(download_length) / float(total_length), '下载中({:.1f}mb/{:.1f}mb)...'.format(download_length/1024/1024, total_length/1024/1024))
                        
                        for i in gradle_version_hash_dirs:
                            filememory.seek(0)
                            with open(os.path.join(i, gradle_version + '.zip'), 'wb') as f:
                                f.write(filememory.read())

                        pbar.progress(1.0, '下载完成')
                        st.rerun()

        else:
            st.success('全部 Gradle 已下载')


        # version_hashmap.keys()
        

if p == '镜像站':
    gradle = st.sidebar.selectbox('Choose Gradle', gradles)

    if gradle:
        st.write(f'你选择了:  {gradle}')

        # if st.button('下载'):
        #     gradle_url = gradle_mirror + gradle
        #     # st.download_button(label='下载', data=gradle_url, file_name=gradle)

        #     st.balloons()

        #     with st.spinner('下载中...'):
        #         st.write(gradle_url)


